package org.sojex.photo.manage;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;

import org.sojex.photo.util.GlobalData;

import android.content.Context;

public class SdcardManager {

	public static boolean isSDCardAvailable() {
		
		String mounted = "mounted";// 正常
		String temp = android.os.Environment.getExternalStorageState();
		// System.out.println("temp=="+temp);
		if (temp.equals(mounted)) {
			return true;
		} else {
			return false;
		}
	}
	
	public synchronized static void Download(Context ctx,String netPath,String localPath){
		InputStream in=null;
		BufferedInputStream reader=null;
		BufferedOutputStream out=null;
		File file=null;
		System.out.println("in DownLoad");
		try {
			if(!isSDCardAvailable()){
				System.out.println("sdcrad不可用！");
				return;
			}
			System.out.println("netPath"+netPath);
			URL m;
			m = new URL(netPath);
			in = (InputStream) m.getContent();
			//in=NetManager.getInstance(ctx).dogetAsStream(netPath);
			reader=new BufferedInputStream(in,1024);
			file=new File(GlobalData.pictureBasePath);
			if(!file.exists())
				file.mkdirs();
			file=new File(localPath);
			out=new BufferedOutputStream(new FileOutputStream(file),1024);
			byte[] bytes=new byte[512];
			int length=0;
			while((length=reader.read(bytes))!=-1){
				out.write(bytes,0,length);
			}
		} catch (Exception e) {
			// TODO Auto-generated catch block
			if(file!=null)
				file.delete();
			e.printStackTrace();
		}finally{
			if(file!=null&&file.length()==0)
				file.delete();
			try {
				if(out!=null)
					out.close();
				if(reader!=null)
					reader.close();
				if(in!=null)
					in.close();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
	}//Download
	
}
